<template>
    <div class="network-setting">
        <h2 class="title">网口配置</h2>
        <div class="form-section">
            <div class="section-title">本机网络配置：</div>
            
            <div class="form-item">
                <label class="form-label">网卡</label>
                <a-select
                    v-model="adapterValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                    @change="handleAdapterSelChange"
                >
                    <a-select-option
                        v-for="adapter in networkAdapters"
                        :key="adapter.id"
                        :value="adapter.id"
                    >
                        {{ adapter.description }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">IP</label>
                <a-select
                    v-model="adaptersIpValue"
                    size="small"
                    placeholder="请选择"
                    :disabled="isDisabled"
                    style="width: 100%;"
                >
                    <a-select-option
                        v-for="ip in currentAdapterIps"
                        :key="ip"
                        :value="ip"
                    >
                        {{ ip }}
                    </a-select-option>
                </a-select>
            </div>

            <div class="form-item">
                <label class="form-label">端口</label>
                <a-input
                    v-model="netPort"
                    size="small"
                    placeholder="请输入端口"
                    :disabled="isDisabled"
                />
            </div>
        </div>

        <div class="form-section">
            <div class="section-title">PLC网络配置：</div>
            
            <div class="form-item">
                <label class="form-label">PLC地址</label>
                <a-input
                    v-model="plcAddress"
                    size="small"
                    placeholder="请输入PLC地址"
                    :disabled="isDisabled"
                />
            </div>

            <div class="form-item">
                <label class="form-label">PLC端口</label>
                <a-input
                    v-model="plcPort"
                    size="small"
                    placeholder="请输入PLC端口"
                    :disabled="isDisabled"
                    :maxlength="5"
                />
            </div>
        </div>

        <div class="form-item">
            <a-button 
                type="primary" 
                size="small" 
                ghost
                @click="handleOpen"
            >
                {{ linkButtonText }}
            </a-button>
        </div>
    </div>
</template>
    
<script>
import DeviceTabManager from '@/api/TabManager/DeviceTabManager'

export default {
    name: 'NetworkSetting',
    props: {
        netAdaptersValue: {
            type: Array,
            required: false,
            default: () => []
        },
        netAdapterIPValue: {
            type: Array,
            required: false,
            default: () => []
        },    
        addressValue: String,
        portValue: String
    },
    data() {
        return {
            deviceTabManager: new DeviceTabManager(),
            networkAdapters: [], // 网卡列表
            // 全局网卡和IP设置
            globalSettings: {
                useNic: true,
                selectedNic: null,
                ip: '0.0.0.0',
                availableIps: ['0.0.0.0']
            },
            netAddress: this.addressValue,
            netPort: this.portValue,
            linkButtonText: '开始监听',
            plcAddress: '',
            plcPort: '',      
            isDisabled: false,
            isOpen: false,
            adapterValue: '',
            adaptersIpValue: '',
            currentAdapterIps: [],
            plcPorts: [],
            netPorts: [],
            clearPorts: [],
            siemensPorts: ['102'],
            mitsubishiPorts: ['5562'],  
            mitsubishiId: ['3109', '3110', '3111'],   
            siemensId: ['3103', '3104', '3105', '3106', '3107', '3108']        
        }
    },
    watch: {
        addressValue(newValue) {
            this.netAddress = newValue
        },
        portValue(newValue) {
            this.netPort = newValue
        },
        netAdaptersValue(newValue) {
            // 保持向后兼容性，但优先使用新的网卡加载方式
            if (newValue && newValue.length > 0 && this.networkAdapters.length === 0) {
                this.networkAdapters = newValue.map((item, index) => ({
                    id: item.value || `adapter_${index}`,
                    description: item.label || `网卡 ${index + 1}`,
                    ipAddresses: []
                }))
                if (this.networkAdapters.length > 0) {
                    this.adapterValue = this.networkAdapters[0].id
                }
            }
        },
        netAdapterIPValue(newValue) {
            // 保持向后兼容性
            if (newValue && newValue.length > 0) {
                this.currentAdapterIps = newValue.map(item => item.value || item)
                if (this.currentAdapterIps.length > 0) {
                    this.adaptersIpValue = this.currentAdapterIps[0]
                }
            }
        }        
    },
    mounted() {
        this.loadNetworkAdapters()
    },
    methods: {
        // 加载网卡列表
        async loadNetworkAdapters() {
            try {
                console.log('🔍 [NetworkSetting] 加载网卡列表')
                const response = await this.deviceTabManager.getNetworkAdapters()
                
                if (response.code !== 0) {
                    console.error('❌ [NetworkSetting] 获取网卡列表失败:', response.message)
                    return
                }
                
                // 解析网卡数据
                let adapters = []
                if (response.data) {
                    if (typeof response.data === 'string') {
                        adapters = JSON.parse(response.data)
                    } else if (Array.isArray(response.data)) {
                        adapters = response.data
                    }
                }
                
                // 处理网卡数据，为每个网卡创建一个合适的数据结构
                this.networkAdapters = adapters.map((adapter, index) => {
                    const ipAddresses = adapter.IpAddresses || []
                    const primaryIp = ipAddresses.length > 0 ? ipAddresses[0] : '0.0.0.0'
                    
                    return {
                        id: adapter.Id || `adapter_${index}`,
                        description: adapter.Description || `网卡 ${index + 1}`,
                        adapterType: adapter.AdapterType || 'Unknown',
                        ipAddresses: ipAddresses,
                        primaryIp: primaryIp,
                        macAddress: adapter.MacAddress || '',
                        gatewayAddresses: adapter.GatewayAddresses || []
                    }
                })
                
                console.log('✅ [NetworkSetting] 网卡列表加载成功:', this.networkAdapters)
                
                // 如果有网卡，默认选择第一个
                if (this.networkAdapters.length > 0) {
                    this.globalSettings.selectedNic = this.networkAdapters[0].id
                    this.globalSettings.availableIps = this.networkAdapters[0].ipAddresses.length > 0 
                        ? this.networkAdapters[0].ipAddresses 
                        : ['0.0.0.0']
                    this.globalSettings.ip = this.globalSettings.availableIps[0]
                    
                    // 同时设置本机网络配置的默认值
                    this.adapterValue = this.networkAdapters[0].id
                    this.currentAdapterIps = this.networkAdapters[0].ipAddresses
                    this.adaptersIpValue = this.currentAdapterIps.length > 0 ? this.currentAdapterIps[0] : ''
                }
                
            } catch (error) {
                console.error('❌ [NetworkSetting] 加载网卡列表失败:', error)
                this.$message.error('加载网卡列表失败: ' + (error.message || '未知错误'))
            }
        },
        
        // 处理网卡切换 (全局设置)
        handleGlobalNicChange(selectedNicId) {
            console.log('🔄 [NetworkSetting] 全局网卡切换:', selectedNicId)
            
            const selectedAdapter = this.networkAdapters.find(adapter => adapter.id === selectedNicId)
            if (!selectedAdapter) {
                console.warn('⚠️ [NetworkSetting] 未找到选中的网卡')
                return
            }
            
            // 更新全局可用IP列表
            this.globalSettings.availableIps = selectedAdapter.ipAddresses.length > 0 
                ? selectedAdapter.ipAddresses 
                : ['0.0.0.0']
            this.globalSettings.ip = this.globalSettings.availableIps[0]
            console.log('✅ [NetworkSetting] 全局IP已更新:', this.globalSettings.ip)
        },

        handleOpen() {
            this.isOpen = !this.isOpen
            console.log('handleOpen button open:', this.isOpen)
            if (!this.adaptersIpValue || this.adaptersIpValue.length === 0) {
                this.$message.warning('检测不到网卡ip')
                return
            }
            if (!this.netPort || this.netPort.length === 0) {
                this.$message.warning('请输入端口号')
                return
            }
            if (!this.plcAddress || this.plcAddress.length === 0) {
                this.$message.warning('请输入PLC地址')
                return
            }
            if (!this.plcPort || this.plcPort.length === 0) {
                this.$message.warning('请输入PLC端口')
                return
            }

            this.linkButtonText = '开始监听'
            if (this.isOpen) {
                this.linkButtonText = '关闭监听'
            }
            this.isDisabled = this.isOpen
            this.$emit('isConnect', this.isDisabled, this.adaptersIpValue, this.netPort, this.plcAddress, this.plcPort)
        },
        updateStatus(bOpen) {
            if (bOpen === 'False') {
                this.isOpen = !this.isOpen
                this.linkButtonText = '开始监听'
                this.isDisabled = false
                this.$notification.warning({
                    message: '警告',
                    description: '监听失败'
                })
            }
        },
        updateInterfaces(para) {
            // 保持向后兼容性
            if (para && para.length > 0) {
                this.networkAdapters = para.map((item, index) => ({
                    id: item.value || `adapter_${index}`,
                    description: item.label || `网卡 ${index + 1}`,
                    ipAddresses: []
                }))
                this.adapterValue = this.networkAdapters.length > 0 ? this.networkAdapters[0].id : ''
            }      
        },   
        updateInterfaceIPs(para) {
            // 保持向后兼容性
            if (para && para.length > 0) {
                this.currentAdapterIps = para.map(item => item.value || item)
                this.adaptersIpValue = this.currentAdapterIps.length > 0 ? this.currentAdapterIps[0] : ''
            }       
        },   
        handleAdapterSelChange(value) {
            console.log('🔄 [NetworkSetting] 网卡切换:', value)
            
            const selectedAdapter = this.networkAdapters.find(adapter => adapter.id === value)
            if (selectedAdapter) {
                this.currentAdapterIps = selectedAdapter.ipAddresses
                this.adaptersIpValue = this.currentAdapterIps.length > 0 ? this.currentAdapterIps[0] : ''
            }
            
            this.getManufacturer(value)// 防止报错
            // remoteTrans.onAdapterSel(value)
        },  
        updatePorts(value) {
            let type = this.getManufacturer(value)
            switch (type) {
                case 'siemens':
                    this.plcPorts = this.siemensPorts
                    this.netPorts = this.siemensPorts  
                    break
                case 'mitsubishi':
                    this.plcPorts = this.mitsubishiPorts
                    this.netPorts = this.mitsubishiPorts
                    break
                default:
                    this.plcPorts = this.clearPorts
                    this.netPorts = this.clearPorts
                    console.log('no ports')
            }

            if (this.plcPorts.length > 0) {
                this.plcPort = this.plcPorts[0].value
            } 
            if (this.netPorts.length > 0) {
                this.netPort = this.netPorts[0].value
            }            
        },
        getManufacturer(value) {
            let type = 'siemens'
            this.mitsubishiId.forEach(item => {
                if (item === value) {
                    type = 'mitsubishi'
                }
            })
            this.siemensId.forEach(item => {
                if (item === value) {
                    type = 'siemens'
                }
            })    
            return type         
        },
        handleSelectPortType() {
            // 端口类型选择处理
            console.log('端口类型已选择')
        }
    }
}
</script>
    
<style scoped lang="scss">
.network-setting {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    max-width: 600px;
    margin: 0 auto;
}
.title {
    text-align: left;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #333;
}
.global-network-selection {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    margin-bottom: 24px;
    border: 1px solid #e8e8e8;
}
.form-section {
    margin-bottom: 20px;
}
.section-title {
    font-weight: 500;
    color: #666;
    margin-bottom: 15px;
    font-size: 14px;
}
.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}
.form-label {
    width: 80px;
    text-align: right;
    margin-right: 15px;
    font-size: 14px;
    color: #333;
    flex-shrink: 0;
}
.action-button {
    margin-left: 95px;
    background-color: #1890ff;
    border-color: #1890ff;
    color: white;
    &:hover {
        background-color: #40a9ff;
        border-color: #40a9ff;
    }
}

// 覆盖 Ant Design 的默认样式
:deep(.ant-select) {
    flex: 1;
}
:deep(.ant-input) {
    flex: 1;
}
</style>
    